package com.iw.adoms.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import com.iw.adoms.dao.DepartmentDao;
import com.iw.adoms.dao.GoodsDao;
import com.iw.adoms.dao.MarchandiseDao;
import com.iw.adoms.dao.OrderLineDao;
import com.iw.adoms.entity.Department;
import com.iw.adoms.entity.Goods;
import com.iw.adoms.entity.Marchandise;
import com.iw.adoms.entity.Order;
import com.iw.adoms.entity.OrderLine;
import com.iw.adoms.entity.neum.DepartType;
import com.iw.adoms.entity.neum.FullStatus;
import com.iw.adoms.entity.neum.Status;
import com.iw.core.orm.Filtration;
import com.iw.core.orm.Filtration.MatchType;
import com.iw.core.orm.hibernate.BaseDao;
import com.iw.core.orm.hibernate.BaseService;
import com.iw.core.security.entity.Users;

@Service
@Transactional
public class OrderService extends BaseService<Order> {
    @Override
    @Resource(name = "orderDao")
    public void setBaseDao(BaseDao<Order> baseDao) {
        this.baseDao = baseDao;
    }

    @Autowired
    private MarchandiseDao marchandiseDao;
    @Autowired
    private OrderLineDao orderLineDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private GoodsDao goodsDao;

    public void commonOrder(Model model, Integer departmentId) {
        List<Marchandise> mList = marchandiseDao.getAllMarchandiseByDepartMentId(departmentId);
        model.addAttribute("mList", mList);
        List<Department> dList = new ArrayList<Department>();// departmentService.findAll();
        Department d = departmentDao.find(departmentId);
        if (d.getDepartment() != null) {
            dList.add(d.getDepartment());
        } else {
            dList.add(d);
        }
        model.addAttribute("dList", dList);
    }

    /**
     * 下订单的操作
     *
     * @param model
     * @param order
     * @param user
     * @param request
     * @param departmentId
     */
    public void order(Model model, Order order, Users user, HttpServletRequest request, Integer departmentId) {
        HttpSession session = request.getSession();
        @SuppressWarnings("unchecked")
        Set<OrderLine> olines = (HashSet<OrderLine>) session.getAttribute("olines");
        String orderInfo = "";
        if (olines != null) {
            order.setOrderCreateTime(new Date());
            order.setCode(String.valueOf(new Date().getTime())); // 订单号中不要数字
            order.setStatus(Status.ORDER_COMMITED);
            FullStatus fStatus = FullStatus.ZDDCL;
            Department department = departmentDao.find(user.getDepartment().getId());
            if (DepartType.MD.v().equals(department.getType().getName())) {
                fStatus = FullStatus.SDDCL;
            }
            order.setfStatus(fStatus);
            order.addLogs(user, "下单成功"); // 记录日志
            this.save(order);
            model.addAttribute("msg", "下单成功！");
            int goodsNumber = 0;
            Double boxNumber = 0.0;
            Double totalCost = 0.0;
            for (OrderLine line : olines) {
                line.setOrder(order);
                boxNumber += line.getBoxNum();
                goodsNumber += line.getItems();
                orderLineDao.save(line);
                Marchandise m = marchandiseDao.find(line.getMarchandise().getId());
                line.setTotalPrice(m.getPrice() * line.getItems()); // 商品总价要通过计算得来，不能来自于前台
                totalCost += line.getTotalPrice();
                orderInfo += "商品名称：" + m.getName() + "，规格：" + m.getSpcification() + "，单价：" + m.getPrice() + "元，订购数量：" + line.getItems() + m.getPackageing() + "，合计：" + line.getTotalPrice() + "元;";
            }
            order.setTotalCost(totalCost);
            order.setGoodsNumber(goodsNumber);
            order.setBoxNumber(boxNumber);
            orderInfo += " 订单总价：" + order.getTotalCost() + "元。";
            order.setOrderInfo(orderInfo);
            this.update(order);
        } else {
            model.addAttribute("msg", "操作失败，订单中无商品尚无任何商品数据！");
        }

        commonOrder(model, departmentId);
    }

    /**
     * 退货单
     *
     * @param model
     * @param order
     * @param user
     * @param request
     * @param departmentId
     */
    public void returnsOrder(Model model, OrderLine line, Order order, Users user, HttpServletRequest request, Integer departmentId, Integer[] rgoods) {

        if (rgoods == null) {
            model.addAttribute("msg", "退货的货物不能为空!");
        } else if (line != null) {
            String orderInfo = "";
            order.setOrderCreateTime(new Date());
            order.setCode("R" + new Date().getTime());
            order.setType(false);
            order.setStatus(Status.HAS_BACKED);

            // 设置退货状态
            FullStatus fStatus = FullStatus.MDTHTD;
            Department department = departmentDao.find(user.getDepartment().getId());
            if (DepartType.SD.v().equals(department.getType().getName())) {
                fStatus = FullStatus.SDTHTD;
            } else {
                fStatus = FullStatus.ZDTHTD;
            }

            order.setfStatus(fStatus);
            order.addLogs(user, "填单完成"); // 记录日志
            this.save(order);
            model.addAttribute("msg", "退货单提交成功！");
            int goodsNumber = 0;
            Double boxNumber = 0.0;
            Double totalCost = 0.0;
            line.setOrder(order);
            boxNumber += line.getBoxNum();
            goodsNumber += line.getItems();
            orderLineDao.save(line);
            Marchandise m = marchandiseDao.find(line.getMarchandise().getId());
            line.setTotalPrice(m.getPrice() * line.getItems()); // 商品总价要通过计算得来，不能来自于前台
            totalCost += line.getTotalPrice();
            orderInfo += "商品名称：" + m.getName() + "，规格：" + m.getSpcification() + "，单价：" + m.getPrice() + "元，退货数量：" + line.getItems() + m.getPackageing() + "，合计：" + line.getTotalPrice() + "元;";

            order.setTotalCost(totalCost);
            order.setGoodsNumber(goodsNumber);
            order.setBoxNumber(boxNumber);
            orderInfo += " 退货单总价：" + order.getTotalCost() + "元。";
            order.setOrderInfo(orderInfo);


            //更新退货店商品的状态为已退货，新增收到退货商品的部门商品货物
            for (Integer gid : rgoods) {
                Goods g = goodsDao.find(gid);

                Goods ng = g.clone(g);
                ng.setDepartment(department);
                ng.setState(Status.WILL_SALE.getValue());
                ng.setOrder(order);
                goodsDao.save(ng);

                g.setState(Status.HAS_BACKED.getValue());
                goodsDao.update(g);
            }

            this.update(order);
        }

        commonOrder(model, departmentId);
    }

    /**
     * 收货，和订单处理
     *
     * @param order
     * @return <option value="ORDER_COMMITED">已提交</option> <option value="ORDER_HAS_RECEIPT">已收货</option> <option value="ORDER_HAS_CANCELED">取消订单</option>
     */
    public boolean saveOrder(Users u, Order order) throws Exception {

        FullStatus fStatus = null;
        Department department = departmentDao.find(u.getDepartment().getId());

        if (DepartType.ZD.v().equals(department.getType().getName())) {
            if (order.getStatus().equals(Status.ORDER_COMMITED)) {
                fStatus = FullStatus.ZDDCL;
            } else if (order.getStatus().equals(Status.ORDER_HAS_RECEIPT)) {
                fStatus = FullStatus.ZDYWC;
            } else if (order.getStatus().equals(Status.ORDER_HAS_CANCELED)) {
                fStatus = FullStatus.ZDYQX;
            }
        } else if (DepartType.SD.v().equals(department.getType().getName())) {
            if (order.getStatus().equals(Status.ORDER_COMMITED)) {
                fStatus = FullStatus.ZDDCL;
            } else if (order.getStatus().equals(Status.ORDER_HAS_RECEIPT)) {
                fStatus = FullStatus.SDYSH;
            } else if (order.getStatus().equals(Status.ORDER_HAS_CANCELED)) {
                fStatus = FullStatus.SDYQX;
            }
        } else if (DepartType.MD.v().equals(department.getType().getName())) {
            if (order.getStatus().equals(Status.ORDER_COMMITED)) {
                fStatus = FullStatus.SDDCL;
            } else if (order.getStatus().equals(Status.ORDER_HAS_RECEIPT)) {
                fStatus = FullStatus.MDYSH;
            } else if (order.getStatus().equals(Status.ORDER_HAS_CANCELED)) {
                fStatus = FullStatus.MDYQX;
            }
        }
        order.setfStatus(fStatus);
        order.setReceivedTime(new Date());
        order.addLogs(u, "处理订单");
        if (order.isNew()) {
            this.save(order);
        } else {
            if (StringUtils.isNotBlank(order.getMemo4())) {
                order.setReceivedDate(new Date());
            }
            this.update(order);
        }
        if (order.getStatus().equals(Status.ORDER_HAS_RECEIPT)) {
            // 更新订单中的货物入库
            List<Goods> list = goodsDao.findList("from Goods where department.id=? and order.id=?", order.getDepartmentTarget().getId(), order.getId());
            for (Goods o : list) {
                Goods g = o.clone(o);
                g.setDepartment(order.getDepartment());
                g.setState(Status.WILL_SALE.getValue());
                g.setOrder(null);
                goodsDao.save(g);
            }
            return true;
        }
        return false;
    }

    /**
     * 修改orderLine订购数量后更新order中的数量和orderInfo
     *
     * @param orderLine
     * @param orderId
     * @throws Exception
     */
    public void updateOrderByOrderLine(Users u, OrderLine orderLine, Integer orderId) throws Exception {

        if (orderLine.getItems() < 1)
            return;
        // 先更新orderline
        orderLineDao.update(orderLine);
        List<OrderLine> orderLines = orderLineDao.findList(new Filtration(MatchType.EQ, orderId, "order.id"));
        Order order = this.find(orderId);
        int goodsNumber = 0;
        Double boxNumber = 0.0;
        String orderInfo = "";
        Double totalCost = 0.0;
        for (OrderLine line : orderLines) {
            line.setOrder(order);
            boxNumber += line.getBoxNum();
            goodsNumber += line.getItems();
            Marchandise m = marchandiseDao.find(line.getMarchandise().getId());
            line.setTotalPrice(m.getPrice() * line.getItems());
            totalCost += line.getTotalPrice(); // 商品总价要通过计算得来，不能来自于前台
            orderInfo += "商品名称：" + m.getName() + "，规格：" + m.getSpcification() + "，单价：" + m.getPrice() + "元，订购数量：" + line.getItems() + m.getPackageing() + "，合计：" + line.getTotalPrice() + "元;";
        }
        order.addLogs(u, "修改商品数量"); // 记录日志
        order.setGoodsNumber(goodsNumber);
        order.setBoxNumber(boxNumber);
        order.setTotalCost(totalCost);
        orderInfo += " 订单总价：" + order.getTotalCost() + "元。";
        order.setOrderInfo(orderInfo);
        this.update(order);
    }

    public void deal(Users u, Order order) {
        FullStatus fStatus = null;
        Department department = departmentDao.find(u.getDepartment().getId());

        if (DepartType.ZD.v().equals(department.getType().getName())) {
            if (order.getStatus().equals(Status.ORDER_WILL_SHIP)) {
                fStatus = FullStatus.ZDDFH;
            } else if (order.getStatus().equals(Status.ORDER_HAS_SHIPED)) {
                fStatus = FullStatus.ZDYFH;
            } else if (order.getStatus().equals(Status.ORDER_HAS_CANCELED)) {
                fStatus = FullStatus.ZDYQX;
            }
        } else if (DepartType.SD.v().equals(department.getType().getName())) {
            if (order.getStatus().equals(Status.ORDER_WILL_SHIP)) {
                fStatus = FullStatus.SDDFH;
            } else if (order.getStatus().equals(Status.ORDER_HAS_SHIPED)) {
                fStatus = FullStatus.SDYFH;
            } else if (order.getStatus().equals(Status.ORDER_HAS_CANCELED)) {
                fStatus = FullStatus.SDYQX;
            }
        } else if (DepartType.MD.v().equals(department.getType().getName())) {
            if (order.getStatus().equals(Status.ORDER_HAS_CANCELED)) {
                fStatus = FullStatus.MDYQX;
            }
        }
        order.setfStatus(fStatus);
        order.setReceivedTime(new Date());
        order.addLogs(u, "处理订单");
        this.update(order);
    }
}
